import fs from 'fs'
import path from 'path'

export default function pagesPlugin() {
  // 创建样式标签 - 开发环境使用
  const createStyleTag = () => `<link rel="stylesheet" href="/src/style.css">`

  let viteConfig

  return {
    name: 'vite-plugin-pages',
    configResolved(resolvedConfig) {
      // 保存 vite 配置
      viteConfig = resolvedConfig
    },

    configureServer(server) {
      // 监听 pages 目录变化
      server.watcher.add('src/pages/**/*.js')

      // 处理 HTML 请求
      server.middlewares.use(async (req, res, next) => {
        const url = req.url?.split('?')[0]
        
        if (url === '/') {
          req.url = '/home.html'
        }
        
        if (url?.endsWith('.html')) {
          const pageName = url.replace('.html', '.js').slice(1);
          const pageScript = path.resolve('src/pages', pageName)

          if (!fs.existsSync(pageScript)) {
            return next()
          }
          
          const template = fs.readFileSync('index.html', 'utf-8')
          
          const html = template
            .replace('<%- title %>', pageName)
            .replace(
              '</head>',
              `${createStyleTag()}\n  </head>`
            )
            .replace(
              '<!-- 入口脚本会被自动注入 -->', 
              `<script type="module" src="/src/pages/${pageName}"></script>`
            )
          
          res.statusCode = 200
          res.setHeader('Content-Type', 'text/html')
          res.end(html)
          return
        }
        next()
      })
    },
    
    config(config) {
      const pagesDir = 'src/pages'
      const pages = {}
      
      if (!fs.existsSync(pagesDir)) {
        fs.mkdirSync(pagesDir, { recursive: true })
      }
      
      // 递归读取所有页面文件
      const readPagesRecursively = (dir, baseDir = '') => {
        const files = fs.readdirSync(dir)
        files.forEach(file => {
          const fullPath = path.join(dir, file)
          const stat = fs.statSync(fullPath)
          
          if (stat.isDirectory()) {
            readPagesRecursively(fullPath, path.join(baseDir, file))
          } else if (file.endsWith('.js')) {
            const relativePath = path.join(baseDir, file)
            const name = relativePath.replace('.js', '')
            pages[name] = path.resolve(dir, file)
          }
        })
      }
      
      readPagesRecursively(pagesDir)

      return {
        build: {
          rollupOptions: {
            input: pages,
            output: {
              dir: 'dist',
              entryFileNames: 'assets/[name].[hash].js',
              chunkFileNames: 'assets/[name].[hash].js',
              assetFileNames: 'assets/[name].[hash][extname]'
            }
          }
        }
      }
    },

    transform(code, id) {
      // 只处理 pages 目录下的 js 文件
      if (id.includes('/src/pages/') && id.endsWith('.js')) {
        // 在每个页面入口添加样式导入
        return {
          code: `import '/src/style.css';\n${code}`,
          map: null
        }
      }
    },

    generateBundle(options, bundle) {
      const template = fs.readFileSync('index.html', 'utf-8')
      
      Object.keys(bundle).forEach(fileName => {
        const chunk = bundle[fileName]
        if (chunk.type === 'chunk' && chunk.isEntry) {
          // 获取相对于 pages 目录的路径
          const relativePath = path.relative(
            path.resolve('src/pages'),
            chunk.facadeModuleId
          ).replace('.js', '')
          
          // 创建对应的 HTML 文件名，保持目录结构
          const htmlFileName = `${relativePath}.html`
          
          // 找到对应的 CSS 文件
          const cssFiles = Object.keys(bundle).filter(name => 
            bundle[name].type === 'asset' && 
            name.endsWith('.css')
          )
          
          let html = template.replace('<%- title %>', relativePath)
          
          // 注入 CSS
          if (cssFiles.length > 0) {
            const cssLinks = cssFiles
              .map(file => `<link rel="stylesheet" href="./${file}">`)
              .join('\n  ')
            html = html.replace('</head>', `  ${cssLinks}\n  </head>`)
          }
          
          // 注入 JS
          html = html.replace(
            '<!-- 入口脚本会被自动注入 -->', 
            `<script type="module" src="./${fileName}"></script>`
          )
          
          this.emitFile({
            type: 'asset',
            fileName: htmlFileName,
            source: html
          })
        }
      })
    }
  }
}